<template>
	<div class="app-container">
		<!-- <div class="push-button-box">
			<el-button class="toggle-button" :class="{ 'active-button': timingId == item.timingId }" @click="handleToggle(item.timingId)">用户</el-button>
			<el-button class="toggle-button" :class="{ 'active-button': timingId == item.timingId }" @click="handleToggle(item.timingId)">应用</el-button>
		</div> -->
		<div class="title-box">
			<el-radio-group v-model="activeTab" style="margin: 10px 0" @change="handleClick">
				<el-radio-button label="user" name="user">用户</el-radio-button>
				<el-radio-button label="application" name="application">应用</el-radio-button>
			</el-radio-group>
			<div class="title-button">
				<el-button plain @click="handleImport">导入</el-button>
				<el-button plain @click="handleCreate(activeTab)" :disabled="isCreated === true">新建</el-button>
			</div>
		</div>
		<div v-if="activeTab == 'user'" class="user">
			<YdTable
				:tableConfig="tableConfig"
				:tableData="tableData"
				@sizeChangeHandler="getList"
				@currentChangeHandler="getList"
				@sortChangeHandler="getList"
				:formData="pushObjectFormData1"
			>
			</YdTable>
		</div>
		<div v-if="activeTab == 'application'" class="application">
			<YdTable
				:tableConfig="tableConfig2"
				:tableData="tableData2"
				@sizeChangeHandler="getList"
				@currentChangeHandler="getList"
				@sortChangeHandler="getList"
				:formData="pushObjectFormData2"
			>
			</YdTable>
		</div>
		<el-divider />

		<el-col :span="8" class="createPushObj" v-if="isCreated === true">
			<div class="create-title">
				<div class="title-text" v-if="formData.id">修改推送对象</div>
				<div class="title-text" v-else>新建推送对象</div>
				<div class="title-button">
					<el-button plain @click="isCreated = false">取消</el-button>
					<el-button plain @click="handleSubmit">保存</el-button>
				</div>

			</div>
			<el-form ref="dataForm" class="create-content" :inline="true" :model="formData" :rules="rules" :label-width="120">
				<el-form-item style="width: 100%" label="对象类型" prop="objType">
					<el-select v-model="formData.objType" placeholder="请选择对象类型" style="width: 100%" :disabled="formData.id">
						<el-option v-for="item in objTypes" :key="item.value" :label="item.label" :value="item.value"></el-option>
					</el-select>
				</el-form-item>
				<div v-if="formData.objType == 'user'">
					<el-form-item style="width: 100%" label="用户名称" prop="nickName">
						<el-input v-model="formData.nickName" placeholder="请输入用户名称" clearable />
					</el-form-item>
					<el-form-item style="width: 100%" label="手机号码" prop="phone">
						<el-input v-model="formData.phone" placeholder="请输入手机号码" clearable />
					</el-form-item>
					<el-form-item style="width: 100%" label="邮箱账号" prop="email">
						<el-input v-model="formData.email" placeholder="请输入邮箱账号" clearable />
					</el-form-item>
					<el-form-item style="width: 100%" label="备注" prop="remark">
						<el-input v-model="formData.remark" placeholder="请输入备注" clearable />
					</el-form-item>
				</div>
				<div v-if="formData.objType == 'application'">
					<el-form-item style="width: 100%" label="应用名称" prop="appName">
						<el-input v-model="formData.appName" placeholder="请输入应用名称" clearable />
					</el-form-item>
					<el-form-item style="width: 100%" label="应用类型">
						<el-input v-model="formData.appType" disabled />
					</el-form-item>
					<el-form-item style="width: 100%" label="网络钩子地址" prop="webHook">
						<el-input v-model="formData.webHook" placeholder="请输入网络钩子地址" clearable />
					</el-form-item>
					<el-form-item style="width: 100%" label="备注">
						<el-input v-model="formData.remark" placeholder="请输入备注" clearable />
					</el-form-item>
				</div>
			</el-form>

		</el-col>


		<!-- 导入弹出层 -->
		<el-dialog
			:key="dialog.imp.key"
			v-model="dialog.imp.open"
			:title="dialog.imp.title"
			width="500px"
			:close-on-click-modal="false"
			append-to-body
			center
			@closed="dialog.imp.key -= 1"
		>
			<div style="text-align: center">
				<el-upload
					ref="uploadRef"
					:headers="dialog.imp.headers"
					:action="dialog.imp.url"
					:data="{}"
					drag
					:auto-upload="false"
					accept=".xls,.xlsx"
					:limit="dialog.imp.limit"
					:before-upload="handleBeforeUpload"
					:on-exceed="handleUploadOnExceed"
					:on-success="handleUploadOnSuccess"
					:on-error="handleUploadOnError"
				>
					<i class="el-icon-upload"></i>
					<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
				</el-upload>
			</div>
			<template #footer>
				<el-button  type="primary" @click="downloadTemplate">下载模板</el-button>
				<el-button  type="primary" @click="handleImport">确 定</el-button>
				<el-button @click="dialog.imp.open = false">取 消</el-button>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="tsx" name="PushObjManagement" setup>
import { ref, reactive, toRefs, onMounted, onActivated, computed, nextTick, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router'; 
import useCurrentInstance from '@/utils/useCurrentInstance';
import type { TabsPaneContext } from 'element-plus';
import {downloadFromBlob} from '@/utils/common'
import {addPushObjectUser,getPushObjectUserList,updatePushObjectUser,deletePushObjectUser, pushObjectUserDownTemplate,importPushObjectUser,addPushObjectApp,getPushObjectAppList,updatePushObjectApp,deletePushObjectApp,pushObjectAppDownTemplate,importPushObjectApp,} from '@/api/ops-workbench/timeSchedule/globalSetting'
import useUserStore from '@/store/modules/userinfo';
const { proxy } = useCurrentInstance();
const router = useRouter();
const route = useRoute();
let isCreated = ref(false);
let activeTab = ref('user');
const dataForm = ref()
let objTypes = [
	{ value: 'user', label: '用户' },
	{ value: 'application', label: '应用' },
]
// 用户列表
let tableData = ref([
]);
// 应用列表
let tableData2 = ref([
]);

// 推送对象用户列表表单
let pushObjectFormData1 = reactive<anyObj>({
	pageNum:1,
	pageSize:10
})
// 推送对象应用列表表单
let pushObjectFormData2 = reactive<anyObj>({
	pageNum:1,
	pageSize:10
})


let formData = ref<FormModelType>({
	objType: 'user',
	appType:'第三方接口'
});
// 用户列表相关
let tableConfig = reactive<TableConfigType>({
	columns: [
		{
			label: '用户名称',
			prop: 'nickName',
			sortable: true,
		},
		{
			label: '手机号码',
			prop: 'phone',
		},
		{
			label: '邮箱账号',
			prop: 'email',
		},
		{
			label: '备注',
			prop: 'remark',
		},
		{
			label: '是否启用',
			prop: 'enable',
			width: 100,
			render: (row: anyObj, val: ApiVal) => {
				// if (proxy.checkRole(['admin']) || proxy.checkPermi(['alarmTemplate:enable'])) {
				return <el-switch v-model={row.enable} activeValue={1} inactiveValue={0} onChange={() => handleEnableChange(row)}></el-switch>;
				// }
				// return (
				//     <el-switch v-model={row.enable} disabled activeValue={0} inactiveValue={1}></el-switch>
				// )
			},
		},
		{
			label: '操作',
			prop: '',
			operation: [
				{
					text: '修改',
					handler: (scope: anyObj) => handleEdit(scope.row,'user'),
					permi: ['globalSetting:pushObj:edit'],
				},
				{
					text: '删除',
					handler: (scope: anyObj) => handleDelete(scope.row),
					permi: ['globalSetting:pushObj:delete'],
				},
			],
		},
	],

	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	loading: false,
});
// 应用列表相关
let tableConfig2 = reactive<TableConfigType>({
	columns: [
		{
			label: '应用名称',
			prop: 'appName',
			sortable: true,
		},
		{
			label: '应用类型',
			prop: 'appType',
		},
		{
			label: 'webHook地址',
			prop: 'webHook',
		},
		{
			label: '备注',
			prop: 'remark',
		},
		{
			label: '是否启用',
			prop: 'enable',
			width: 100,
			render: (row: anyObj, val: ApiVal) => {
				// if (proxy.checkRole(['admin']) || proxy.checkPermi(['alarmTemplate:enable'])) {
				return <el-switch v-model={row.enable} activeValue={1} inactiveValue={0} onChange={() => handleEnableChange(row)}></el-switch>;
				// }
				// return (
				//     <el-switch v-model={row.enable} disabled activeValue={0} inactiveValue={1}></el-switch>
				// )
			},
		},
		{
			label: '操作',
			prop: '',
			operation: [
				{
					text: '修改',
					handler: (scope: anyObj) => handleEdit(scope.row, 'application'),
					permi: ['globalSetting:pushObj:edit'],
				},
				{
					text: '删除',
					handler: (scope: anyObj) => handleDelete(scope.row),
					permi: ['globalSetting:pushObj:edit'],
				},
			],
		},
	],

	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	loading: false,
});

const uploadRef = ref()

let dialog = reactive({
	addOrUpdate: {
		// 打开状态
		open: false,
		// 标题
		title: '',
		// 表单数据
		form: {},
		// 按钮加载中状态
		btnLoading: false,
		// 表单校验规则
	},
	imp: {
		url: '/jimu/addresseeUser/upload',
		key: -1,
		// 打开状态
		open: false,
		// 标题
		title: '导入',
		// 上传请求头
		headers: {
			Authorization: 'Bearer ' + useUserStore().access_token,
			VERSION:"dengfazhu"
		},
		// 最多导入数
		limit: 1,
		// 下载模板按钮状态
		downloadTemplateBtnLoading: false,
		// 导入确定按钮状态
		importSubmitBtnLoading: false,
	},
});

const rules = reactive<anyObj>({
	objType: [{required: true, message: "请选择对象类型", trigger: "blur"}],
	nickName: [{required: true, message: "请输入用户名称", trigger: "blur"}],
	phone: [{required: true, message: "请输入手机号码", trigger: "blur"},{ pattern: /^1[3456789]\d{9}$/, message: "手机号码格式错误", trigger: "blur"}],
	email: [{required: true, message: "请输入邮箱账号", trigger: "blur"}],
	appName: [{required: true, message: "请输入应用名称", trigger: "blur"}],
	webHook: [{required: true, message: "请输入网络钩子地址", trigger: "blur"}],
})

watch( () => activeTab.value, (newval:string) => {
	let userUrl = import.meta.env.DEV ? import.meta.env.VITE_APP_BASE_API + '/jimu/addresseeUser/upload' : '/jimu/addresseeUser/upload';
	let appUrl = import.meta.env.DEV ? import.meta.env.VITE_APP_BASE_API + '/jimu/addresseeApp/upload' : '/jimu/addresseeApp/upload'
	let url = newval === 'user' ? userUrl : appUrl;
	console.log('watch',url)
	dialog.imp.url = url;
})

onMounted(()=>{
	getUserList();
	getAppList();
})


function getList() {
	if(activeTab.value === 'user'){
		getUserList()
	}else {
		getAppList()
	}

}

function getUserList(){
	console.log('getuserlist')
	getPushObjectUserList(pushObjectFormData1).then((res:ApiResponse) => {

			if(res.code === 0){
				res.data.records.forEach((item:any) => {
					if(item.enable === null){
						item.enable = 1
					}
				})
				tableData.value = res.data.records;
				tableConfig.pagination!.total  = res.data.total;

			}else {
				proxy?.$message(res.msg)
			}
		})
}

function getAppList(){
	console.log('getapplist')
	getPushObjectAppList(pushObjectFormData2).then((res:ApiResponse) => {
			if(res.code === 0){
				res.data.records.forEach((item:any) => {
					if(item.enable === null){
						item.enable = 1
					}
				})
				tableData2.value = res.data.records;
				tableConfig2.pagination!.total = res.data.total;
			}else {
				proxy?.$message(res.msg)
			}
		})
}

// 删除
function handleDelete(row: anyObj) {
	if(activeTab.value === 'user'){
		proxy.$modal
		.confirm('确定删除推送用户' + row.nickName + '吗？', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			cancelButtonClass: 'confirm-rigth-cancel-button',
			type: 'warning',
		})
		.then(() => {
			deletePushObjectUser(row.id).then((res:ApiResponse)=>{
				if(res.code !==0){
					proxy.$message.error(res.msg);
					return;
				}
				proxy?.$message.success('删除成功');
				getList()
			})
		})
	}else {
		proxy.$modal
		.confirm('确定删除推送应用' + row.appName + '吗？', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			cancelButtonClass: 'confirm-rigth-cancel-button',
			type: 'warning',
		})
		.then(() => {
			deletePushObjectApp(row.id).then((res:ApiResponse)=>{
				if(res.code !==0){
					proxy.$message.error(res.msg);
					return;
				}
				proxy?.$message.success('删除成功');
				getList()
			})
		})
	}
}

// 修改
function handleEdit(row: anyObj,objType:string) {
	dataForm.value?.resetFields();
	formData.value = Object.assign({objType:objType},row);
	isCreated.value = true
	console.log(' handleEdit', formData)

}
// 导入
function handleImport(){
	console.log('dialog.imp.open',dialog.imp.open)
	if (!dialog.imp.open) {
		dialog.imp.open = true;
		nextTick(() => {
			uploadRef.value?.clearFiles();
		});

		return;
	}
	uploadRef.value.submit();

}
// 下载导入模板
function downloadTemplate() {
	if(activeTab.value === 'user'){
		pushObjectUserDownTemplate().then((res) => {
			downloadFromBlob(res, '推送对象用户模板').then((o) => {
				if (!o.flag) {
					proxy.$modal.msgWarning(o.msg);
				}
			});
		});
	}else {
		pushObjectAppDownTemplate().then((res) => {
			downloadFromBlob(res, '推送对象应用模板').then((o) => {
				if (!o.flag) {
					proxy.$modal.msgWarning(o.msg);
				}
			});
		});
	}
}
 // 上传前
function handleBeforeUpload(file: anyObj) {
	const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1);
	const whiteList = ['xls', 'xlsx'];
	if (whiteList.indexOf(fileSuffix) === -1) {
		proxy.$modal.msgError('上传文件只能是 xls、xlsx 格式');
		return false;
	}
}
// 上传超过最大数量限制时
function handleUploadOnExceed() {
	proxy.$modal.msgWarning('最多上传' + dialog.imp.limit + '个文件');
}
// 导入成功
function handleUploadOnSuccess(res:ApiResponse) {
	if (res.code !== 0) {
		proxy.$modal.msgError(res.msg);
		return;
	}
	dialog.imp.open = false;
	proxy.$modal.msgSuccess("导入成功");
	if(activeTab.value === 'user'){
		getUserList()
	}else {
		getAppList();
	}

}
// 导入失败
function handleUploadOnError() {
	dialog.imp.open = true;
	proxy.$modal.msgError('导入失败');
}
// 新建
function handleCreate(val: string) {
	dataForm.value?.resetFields();
	resetForm(formData.value?.objType)
	nextTick(() => {
		console.log('create', formData.value)
		isCreated.value = true;
	})
	
}

// 提交

function handleSubmit(){
	console.log("formData.value",formData.value)
	if(formData.value.id){
		handleUpdate()
	}else {
		handleSave()
	}
}

// 保存
function handleSave() {
	dataForm.value?.validate((valid: boolean, _msg: any) => {
		if (valid) {
			let params = JSON.parse(JSON.stringify(formData.value))
			delete params.objType
			params.enable = 1; //默认启用

			if(activeTab.value == 'user'){
				// 保存推送对象用户
				
				addPushObjectUser(params).then((res:ApiResponse) => {
					if(res.code === 0){
						proxy?.$message.success("保存成功")
						dataForm.value?.resetFields();
						resetForm(formData.value.objType)
						getList()
					}
				})

			}else {
				// 保存推送对象应用
				addPushObjectApp(params).then((res:ApiResponse) => {
					if(res.code === 0){
						proxy?.$message.success("保存成功")
						dataForm.value?.resetFields();
						resetForm(formData.value.objType)
						getList()
					}
				})


			}
		}
	});
}

// 修改
function handleUpdate() {
	dataForm.value?.validate((valid: boolean, _msg: any) => {
		if (valid) {
			updateSubmit()
		}
	});
}

function updateSubmit(row?:any){
	let data = row || formData.value;
	let params = JSON.parse(JSON.stringify(data))
	delete params.objType
	if(activeTab.value == 'user'){
		// 修改推送对象用户
		
		updatePushObjectUser(params).then((res:ApiResponse) => {
			if(res.code === 0){
				proxy?.$message.success("修改成功")
				isCreated.value = false;
				getList()
			}
		})

	}else {
		// 修改推送对象应用
		updatePushObjectApp(params).then((res:ApiResponse) => {
			if(res.code === 0){
				proxy?.$message.success("修改成功")
				isCreated.value = false;
				getList()
			}
		})


	}
}




//是否启用
function handleEnableChange(row: anyObj) {
	const isStatus = row.enable;
	let text = '启用';
	if (isStatus == 0) {
		text = '禁用';
	}
	proxy.$modal
		.confirm('确定' + text + '吗？', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			cancelButtonClass: 'confirm-rigth-cancel-button',
			type: 'warning',
		})
		.then(() => {
			updateSubmit(row)
		})
		.catch(function (err: any) {
			console.log('error',err)
			row.enable = row.enable === 0 ? 1 : 0;
		});
}

// 切换对象类型
const handleClick = (tab: TabsPaneContext) => {
	console.log(tab)

	formData.value.objType = tab
};

function resetForm(objType: string){
	for(let key in formData.value){
		formData.value[key] = '';
	}
	console.log('resetForm', formData.value)

	formData.value.objType = objType
	formData.value.appType = "第三方接口"
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.title-box{
	display: flex;
	justify-content: space-between;
	align-items: center;
}
.createPushObj{
	.create-title {
		display: flex;
		justify-content: space-between;
		.title-text {
			font-size: 18px;
			font-weight: bold;
		}
	}
	.create-content{
		margin-top: 20px;
	}
}
</style>
